﻿using Application.Adapter;
using Application.Common.Extensions;
using Application.Common.Interface;
using Domain;
using Domain.Models.Cmd;
using MediatR;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TouchSocket.Core;

namespace Application.App.Queries
{
    public class GetStateQuery:IRequest<Result>
    {
        public string deviceId { get; set; }
    }

    public class GetStateQueryHandle : IRequestHandler<GetStateQuery, Result>
    {
        private readonly ICustomTcpClient _client;
        public GetStateQueryHandle(ICustomTcpClient client)
        {
            _client = client;
        }
        public async Task<Result> Handle(GetStateQuery request, CancellationToken cancellationToken)
        {
            Consts.CommandPackageLength.TryGetValue(Domain.Enums.DataType.查询设备命令下, out var packageLength);
            var buffer = new List<byte>() { Consts.StartByte, packageLength };
            buffer.AddRange(request.deviceId.HexStringToByteArray());
            buffer.Add(((int)Domain.Enums.DataType.查询设备命令下).ToByte());
            var vaildCode = buffer.GetVaildByteCode();
            buffer.Add(vaildCode);
            buffer.Add(Consts.EndByte);
            Console.WriteLine($"App Send Command Req:{Convert.ToHexString(buffer.ToArray())}");

            try
            {
                //_client.Send(buffer.ToArray());
                var res = (DeviceReplySelect)((BetweenAndRequestInfo) _client.SendThenReceive(buffer.ToArray(), TouchSocket.Sockets.AdapterFilter.WaitAdapter).RequestInfo).Data;
                return Result.FromSuccess(JsonConvert.SerializeObject(res));
            }
            catch (Exception e)
            {
                return Result.FromError(e.Message);
            }
        }
    }

}
